<template>
  <div class="form-container">
    <!-- 第一个卡片 -->
    <el-card class="form-card" shadow="always" style="width: 900px">
      <div>报价信息</div>
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        label-width="auto"
        class="demo-ruleForm"
        :size="formSize"
        status-icon
      >
        <!-- 第一行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="机器品牌" prop="region">
              <el-select
                v-model="ruleForm.machineBrand"
                placeholder="请选择机器品牌"
                style="width: 100%; height: 40px"
              >
                <el-option label="上海" value="shanghai" />
                <el-option label="北京" value="beijing" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="机器型号" prop="count">
              <el-select
                v-model="ruleForm.machineModel"
                placeholder="请选择机器型号"
                style="width: 100%; height: 40px"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <!-- 第二行 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="公司是否做过" prop="isdone">
              <el-select
                v-model="ruleForm.isdone"
                placeholder="请选择"
                style="width: 100%; height: 40px"
              >
                <el-option label="是" value="1" />
                <el-option label="否" value="0" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="产品类型" prop="productType">
              <el-tree-select
                v-model="ruleForm.productType"
                :data="categoryOptions"
                check-strictly
                :render-after-expand="false"
                placeholder="请选择产品类型"
                :props="{
                  label: 'label',
                  value: 'value',
                  children: 'children'
                }"
                style="width: 100%; height: 100px"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </el-card>

    <!-- 第二个卡片（产品信息 + 表格） -->
    <el-card class="form-card" shadow="always" style="width: 900px">
      <div>产品信息</div>
      <el-table :data="tableRows" style="width: 100%; margin-top: 20px">
        <el-table-column label="产品名称" width="90px" align="center">
          <template #default="{ row }">
            <el-input v-model="row.productName" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="图号" width="100px" align="center">
          <template #default="{ row }">
            <el-input v-model="row.figureNumber" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="材质" width="120px" align="center">
          <template #default="{ row }">
            <el-input v-model="row.material" placeholder="请输入" />
          </template>
        </el-table-column>
        <el-table-column label="件数(pcs)" width="110px" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.items"
              placeholder="请输入"
              type="number"
              @input="validatePositiveNumber('items', row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="预计单重(kg/件)" width="110px" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.unitWeight"
              placeholder="请输入"
              type="number"
              @input="validatePositiveNumber('unitWeight', row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="单价(USD/pcs)" width="110px" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.unitPrice"
              placeholder="请输入"
              type="number"
              @input="validatePositiveNumber('unitPrice', row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="交期(天)" width="110px" align="center">
          <template #default="{ row }">
            <el-input
              v-model="row.delivery"
              placeholder="请输入"
              type="number"
              @input="validatePositiveNumber('delivery', row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="105px" align="center">
          <template #default="{ row, $index }">
            <el-button type="danger" size="small" @click="removeRow($index)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 产品信息表 -->
      <el-row
        class="product-info-form"
        :gutter="40"
        style="margin-top: 20px; padding-left: 30px"
      >
        <span>总重量:</span>
        <el-col :span="5">
          <el-input v-model="ruleForm.totalWeight" placeholder="总重量" />
        </el-col>
        <span>总金额:</span>
        <el-col :span="5">
          <el-input v-model="ruleForm.totalAmount" placeholder="总金额" />
        </el-col>
        <span>*总托数:</span>
        <el-col :span="5">
          <el-input v-model="ruleForm.totalPallet" placeholder="总托数" />
        </el-col>
      </el-row>
      <el-row
        class="product-info-form"
        :gutter="20"
        style="margin-top: 20px; padding-left: 20px"
      >
        <span>预估总体积(方):</span>
        <el-col :span="4">
          <el-input v-model="ruleForm.totalVolume" placeholder="请输入" />
        </el-col>
        <span>总交期(天):</span>
        <el-col :span="5">
          <el-input v-model="ruleForm.totalDelivery" placeholder="请输入" />
        </el-col>
        <span>报价有效期:</span>
        <el-col :span="5">
          <el-select v-model="ruleForm.validity" placeholder="请选择">
            <el-option label="30天" value="30" />
            <el-option label="60天" value="60" />
            <el-option label="90天" value="90" />
          </el-select>
        </el-col>
      </el-row>
      <el-row
        class="product-info-form"
        :gutter="20"
        style="margin-top: 20px; padding-left: 20px"
      >
        <span>模型情况说明:</span>
        <el-col :span="12">
          <el-input v-model="ruleForm.modelDesc" placeholder="模型情况说明" />
        </el-col>
      </el-row>
      <!-- 提交按钮 -->
      <el-button @click="submitForm" type="primary" style="margin-top: 30px"
        >提交</el-button
      >
    </el-card>
  </div>
</template>

<script lang="ts" setup>
import { reactive, ref, onMounted } from "vue";
import { getCategoryList, saveProductInquiry } from "@/api/supplier/supplier";
import { ElMessage } from "element-plus";

// 整合后的数据对象
const ruleForm = reactive({
  machineBrand: "",
  machineModel: "",
  isdone: "",
  productType: "",
  totalWeight: "",
  totalAmount: "",
  totalPallet: "",
  totalVolume: "",
  totalDelivery: "",
  validity: "",
  modelDesc: ""
});

// 初始化表格数据，至少一行数据
const tableRows = reactive([
  {
    productName: "",
    figureNumber: "",
    material: "",
    items: 0,
    unitWeight: 0,
    unitPrice: 0,
    delivery: 0
  }
]);

// 通过设置合法的值，确保 formSize 是合法的
const formSize = ref<"default" | "small" | "large">("default");

// 获取产品类型的树形数据
const categoryOptions = ref<any[]>([]);

// 获取产品分类数据
const fetchCategories = async () => {
  try {
    const params = {
      page: 1,
      pageSize: 10
    };

    const response = await getCategoryList(params);

    if (response.code === 200) {
      const categoriesData = response.data.data;

      const categoryMap = new Map<
        string,
        { label: string; value: string; children: any[] }
      >();

      categoriesData.forEach((category: any) => {
        const code = category.code.toString();
        const label = category.type_name;

        if (!categoryMap.has(code)) {
          categoryMap.set(code, {
            label,
            value: code,
            children: []
          });
        }
      });

      categoriesData.forEach((category: any) => {
        const code = category.code.toString();
        const parentCode = category.pid.toString();

        if (parentCode !== "1" && categoryMap.has(parentCode)) {
          categoryMap.get(parentCode)?.children.push(categoryMap.get(code));
        }
      });

      categoryOptions.value = Array.from(categoryMap.values()).filter(
        (category: any) => category.value.length === 2
      );
    } else {
      ElMessage.error("加载分类失败");
    }
  } catch (error) {
    ElMessage.error("获取分类数据出错");
    console.error("获取产品类型失败:", error);
  }
};

// 确保件数、预计单重、单价、交期不可被调为负数
const validatePositiveNumber = (field: string, row: any) => {
  if (row[field] < 0) {
    row[field] = 0;
  }
};

// 组件挂载时获取数据
onMounted(() => {
  fetchCategories();
});

// 删除行方法
const removeRow = (index: number) => {
  tableRows.splice(index, 1);
};

// 提交表单
const submitForm = () => {
  // 先处理表格中的数据，确保所有值是正确的类型
  const row = tableRows[0]; // 获取表格中的第一行数据（如果表格有多行，可以根据需求做处理）

  const formData = {
    delivery: Number(row.delivery) || 0,
    figureNumber: row.figureNumber || "",
    id: 0,
    isdone: Number(ruleForm.isdone) || 0,
    items: Number(row.items) || 0,
    machineBrand: ruleForm.machineBrand || "",
    machineModel: ruleForm.machineModel || "",
    material: row.material || "",
    modelDesc: ruleForm.modelDesc || "",
    productName: row.productName || "",
    productType: ruleForm.productType || "",
    totalAmount: Number(ruleForm.totalAmount) || 0,
    totalDelivery: Number(ruleForm.totalDelivery) || 0,
    totalPallet: Number(ruleForm.totalPallet) || 0,
    totalVolume: Number(ruleForm.totalVolume) || 0,
    totalWeight: Number(ruleForm.totalWeight) || 0,
    unitPrice: Number(row.unitPrice) || 0,
    unitWeight: Number(row.unitWeight) || 0,
    validity: Number(ruleForm.validity) || 0
  };

  // 打印提交数据，检查格式
  // console.log("提交的数据>>>:", formData);

  // 调用保存 API
  saveProductInquiry(formData)
    .then(response => {
      if (response.code === 200) {
        ElMessage.success("提交成功");
      } else {
        ElMessage.error("提交失败");
      }
    })
    .catch(error => {
      console.error("提交请求失败:", error);
    });
};
</script>

<style scoped>
.form-container {
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  margin-top: 40px;
}

.form-card {
  width: 800px;
  margin-bottom: 20px;
}

.demo-ruleForm {
  margin-top: 20px;
}

.el-form-item {
  margin-bottom: 20px;
}

.product-info-form {
  display: flex;
  align-items: center;
}

.product-info-form > span {
  line-height: 32px;
}
</style>
